package com.shengchang.hu.supervision.UI;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.shengchang.hu.supervision.Api.PrintHelper;
import com.shengchang.hu.supervision.Application.App;
import com.shengchang.hu.supervision.R;
import com.shengchang.hu.supervision.ToolBar.InBoundBar;
import com.shengchang.hu.supervision.Utils.BarcodeUtil;
import com.shengchang.hu.supervision.Utils.BluetoothLeClass;
import com.shengchang.hu.supervision.Utils.Bluetooth_Scale;
import com.shengchang.hu.supervision.Utils.Contants;
import com.shengchang.hu.supervision.Utils.PubFunction;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class CheckOutActivity extends BaseActivity implements View.OnClickListener {



    private InBoundBar checkedbar;

    private Button  printcode;
    private  TextView times;
    private  TextView count;

    private  String maccode;
    /*打印功能*/

    String count1;
    String weight1;
    private String inTime;
    private String inCode;
    private String incode = "1233";
    //蓝牙连接
    public static Context context;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeClass mBLE;
    private boolean mScanning;
    private Handler mHandler;
    final Boolean SendMoudle=true;  //  这个表示是连接称重模块
    Boolean b_scaleIsConnect=Boolean.FALSE;
    SCALENOW scalenow=new SCALENOW();
    int BluetoothType=2;
    public Bluetooth_Scale btScale=null;
    public BluetoothLeClass bleScale=null;
    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;
    Boolean bisClosed=false;
    StringBuilder sb=new StringBuilder();
    String  m_Broadcastname = "com.barcode.sendBroadcast";
   MyCodeReceiver receiver = new MyCodeReceiver();
    private long mPressedBackTime;
    int countNum = 0;
    String weightCount="0";
    double plusweight=0;
    OkHttpClient okHttpClient = new OkHttpClient();
    /*打印*/
    private int mLineTextSize = 18;
    private int mTitleTextSize = 20;
    private int mKeyTextSize = 26;
    private boolean titleBold = true;

    PrintHelper printHelper = null;
    private PrintHelper.PrintType mTitleType = PrintHelper.PrintType.Centering;
    private static final String Terminal_checkRubbishInRepeat = Contants.Terminal_checkRubbishInRepeat;
    private static final String SCAN_QRCODE_RUKU = Contants.SCAN_QRCODE_RUKU;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_check_out);
        checkedbar=findViewById(R.id.checkedbar);
        checkedbar.setLeftTitleClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        Intent intent = getIntent();
        maccode = intent.getStringExtra("maccode");
        initView();
        BleConnction();
        initPrinter();

        }

    private void initView() {

        printcode=findViewById(R.id.printcode);
        printcode.setOnClickListener(this);
        times=findViewById(R.id.time);
        count=findViewById(R.id.count);

    }

    private void BleConnction() {
        try {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        mHandler=new Handler()
        {
            public void handleMessage(Message msg)
            {
                switch(msg.what)
                {
                    case 2:
                        if(msg.arg1<2) {

                            b_scaleIsConnect=Boolean.FALSE;
                        }
                        else {
                            b_scaleIsConnect = Boolean.TRUE;
                            if(SendMoudle)
                            {

                            }
                        }
                        break;

                }
            }
        };
        mBluetoothAdapter.enable();
        if(btScale==null)btScale = new Bluetooth_Scale(CheckOutActivity.this, mHandler);
        btScale.SetOnReceivedDataListener(new Bluetooth_Scale.onReceivedDataListener() {
            @Override
            public void onReceivedData(byte[] buf) {
                OnReceivedData(buf);
            }
        });
        if(bleScale==null)
        {
            bleScale = new BluetoothLeClass(CheckOutActivity.this);
            bleScale.initialize();
            bleScale.setOnConnectListener(new BluetoothLeClass.OnConnectListener() {
                @Override
                public void onConnect(BluetoothGatt gatt) {
                    Toast.makeText(CheckOutActivity.this,"BLE Connected",Toast.LENGTH_SHORT).show();
                }
            });
            bleScale.setOnDisconnectListener(new BluetoothLeClass.OnDisconnectListener() {
                @Override
                public void onDisconnect(BluetoothGatt gatt) {
                    Toast.makeText(CheckOutActivity.this,"BLE Lost",Toast.LENGTH_SHORT).show();
                }
            });
            bleScale.setOnConnectListener(new BluetoothLeClass.OnConnectListener() {
                @Override
                public void onConnect(BluetoothGatt gatt) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(CheckOutActivity.this, "蓝牙连接成功", Toast.LENGTH_SHORT).show();
                        }
                    });

                }
            });
            bleScale.setOnDisconnectListener(new BluetoothLeClass.OnDisconnectListener() {
                @Override
                public void onDisconnect(BluetoothGatt gatt) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(CheckOutActivity.this,"蓝牙没有连接成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
            bleScale.setOnDataAvailableListener(new BluetoothLeClass.OnDataAvailableListener() {
                @Override
                public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {

                }

                @Override
                public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                    byte[] buffer =characteristic.getValue();
                    OnReceivedData(buffer);
                }
            });
        }

        if(maccode.length()>0) {
            //ble或者双模模块
            if ((BluetoothType == BluetoothDevice.DEVICE_TYPE_LE)) {
                if ((bleScale != null) && bleScale.isConnect) {
                    bleScale.disconnect();
                }
                bleScale.connect(maccode);
                WriteConfig();
            } else {
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(maccode);
                if (device != null) {
                    btScale.connect(device);
                    WriteConfig();
                }
            }
        }
        ReadConfig();
        if(!TextUtils.isEmpty(maccode)&&maccode.length()>0) {
            //ble或者双模模块
            if ((BluetoothType == BluetoothDevice.DEVICE_TYPE_LE)) {
                if ((bleScale != null) && bleScale.isConnect) {
                    bleScale.disconnect();
                }
                bleScale.connect(maccode);
            } else {
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(maccode);
                if (device != null) {
                    btScale.connect(device);
                }
            }
        }



    }
    byte[] strdata=new byte[100];
    int pStrdata=0;
    void OnReceivedData(byte buf[])
    {
        int bytes=buf.length;
        for(int i = 0; i < bytes; i++)
        {
            if(buf[i]==0x2)pStrdata=0;
            else  if((buf[i]==0x0a)||(buf[i]==0x03))
            {
                GetWeight(strdata,pStrdata);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {

                        if(scalenow.bOverFlag)
                        {

                        }
                        else {

                        }

                    }
                });

                pStrdata=0;
            }
            else
            {
                strdata[pStrdata] = buf[i];
                if(++pStrdata>=100)pStrdata=0;
            }
        }
    }

    void GetWeight(byte[] databuf,int datalenght)
    {
        float f=0;
        int dot=1;
        scalenow.bOverFlag=false;
        scalenow.bWeiStaFlag=false;
        switch(databuf[0])
        {
            case 'o':
            case 'O':
                scalenow.bOverFlag=true;
                break;
            case 'u':
            case 'U':
                scalenow.bWeiStaFlag=false;
                break;
            case 's':
            case 'S':
                scalenow.bWeiStaFlag=true;
                break;
        }
        if(datalenght>7) {
            for(int i=0;i<7;i++) {
                if (databuf[i + 6 + 1] == '.') {
                    dot = -1;
                } else {
                    if (dot >= 0) {
                        f = f * 10 + ((databuf[i + 6 + 1] == ' ') ? 0 : (databuf[i + 6 + 1] - '0'));
                    } else {
                        f += Math.pow(10, dot) * (databuf[i + 6 + 1] - '0');
                        dot--;
                    }
                }
            }
            if (databuf[6] == '-') f *= -1;
        }
        if(dot<0)dot=(-dot)-1;
        else dot=0;
        scalenow.fformatNetWeight=f;
        scalenow.sformatNetWeight=String.format("%1."+String.valueOf(dot)+"f",f);
        if(datalenght>14)
        {
            scalenow.sUnit=new String(databuf,14,datalenght-14);
        }
        scalenow.bZeroFlag=(f==0);
    }
    public void ReadConfig() {
        SharedPreferences settings = getSharedPreferences(PubFunction.PREFS_NAME, Context.MODE_PRIVATE);
        maccode = settings.getString("BluetoothAddress", "");
        BluetoothType = settings.getInt("BluetoothType", 0);
    }
    public void WriteConfig()
    {

        SharedPreferences settings = getSharedPreferences(PubFunction.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("BluetoothType", BluetoothType);
        editor.putString("BluetoothAddress", maccode);
        editor.commit();
    }

    public static class SCALENOW {
        public String sformatNetWeight="0";
        public String sUnit=" g ";
        public float fformatNetWeight;
        public boolean bZeroFlag;
        public boolean bWeiStaFlag;
        public boolean bOverFlag;
    }
//打印机注册
public void initPrinter() {
    printHelper = new PrintHelper();
    printHelper.Open(this);
}
    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerBroadcast();
        }


    /**
     * 扫描信息获取
     */
    public void registerBroadcast() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(m_Broadcastname);
        registerReceiver(receiver, intentFilter);
    }

    public class MyCodeReceiver extends BroadcastReceiver
    {
        private static final String TAG = "MycodeReceiver";
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(m_Broadcastname)) {
                String str = intent.getStringExtra("BARCODE");
                if (!"".equals(str)  ) {

                    showProgressDialog();
                    ChecedQRRequest(str);

                    }
            }
        }
    }


    private void ChecedQRRequest(final String barcode) {

        RequestBody formBody = new FormBody.Builder()
                .add("id", App.getApp().getToken())
                .add("rubbishCode", barcode)
                .build();
        Request request = new Request.Builder()
                .url(Terminal_checkRubbishInRepeat)
                .post(formBody)
                .build();
        Log.d("ckRubbishInRepeat", Terminal_checkRubbishInRepeat + "?id=" + App.getApp().getToken() + "&rubbishCode=" +
                barcode);
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }
                        });                //此处会发生异常//
                    }
                }).start();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String checedstr = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ChecedResPonse(checedstr,barcode);
                    }
                });

            }
        });
    }

    private void ChecedResPonse(String checedstr,String  barcode) {
        try {
            JSONObject checedjson = new JSONObject(checedstr);
            String checedjsonString = checedjson.getString("message");
            if (checedjsonString.equals("20005")) {
                dismissProgressDialog();
                countNum++;
                count.setText(countNum + "    袋");
                ScannerQRCdeRequest(barcode);
                } else if (checedjsonString.equals("20006")) {
                dismissProgressDialog();
                showShortToast("不可重复之前操作");
            } else if (checedjsonString.equals("20009")) {
                dismissProgressDialog();
                showShortToast("类型不符合");
            } else if (checedjsonString.equals("20008")) {
                dismissProgressDialog();
                showShortToast("无满足条件对象");
            }else if (checedjsonString.equals("20010")){
                dismissProgressDialog();
                countNum++;
                count.setText(countNum + "    袋");

                showShortToast("重量警告");
            }else if (checedjsonString.equals("20011")){
                dismissProgressDialog();
                countNum++;
                count.setText(countNum + "   袋");

                showShortToast("入库成功");
            }else if (checedjsonString.equals("20017")){
                dismissProgressDialog();

            }else if (checedjsonString.equals("医废非产生状态（入库或者出库）")){
                dismissProgressDialog();

                showShortToast("医废非产生状态（入库或者出库）");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            JSONObject DataMsg = new JSONObject(checedstr);
            weightCount = DataMsg.getString("weight");
            times.setText(weightCount);

        } catch (JSONException e) {
            e.printStackTrace();
        }


    }
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.printcode:

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                PrintMessge();
                            }
                        }, 20);                //此处会发生异常//
                    }
                }).start();


                break;

        }
    }
    private void ScannerQRCdeRequest(String barcode) {
        RequestBody formBody = new FormBody.Builder()
                .add("id", App.getApp().getToken())
                .add("rubbishCode", barcode)
                .build();
        Request request = new Request.Builder()
                .url(SCAN_QRCODE_RUKU)
                .post(formBody)
                .build();
        Log.d("SCAN_QRCODE_RUKU", SCAN_QRCODE_RUKU + "?id=" + App.getApp().getToken()
                + "&rubbishCode=" + barcode);
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                dismissProgressDialog();
                                // 放在UI线程弹Toast
                                showLongToast("请求失败，请确认网络");
                            }
                        });                //此处会发生异常//
                    }
                }).start();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String QRloginstr = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        QRLoginResPonse(QRloginstr);
                    }
                });

            }
        });

    }

    private void QRLoginResPonse(String qRloginstr) {
        try {
            JSONObject jsonObject = new JSONObject(qRloginstr);
            String loginMsg = jsonObject.getString("message");
            if (loginMsg.equals("20004")) {
                dismissProgressDialog();
                showShortToast("请求异常");
            } else if (loginMsg.equals("20005")) {
                dismissProgressDialog();
                showShortToast("入库成功");

                } else if (loginMsg.equals("20017")){
                dismissProgressDialog();
                showShortToast("重量小于等于零");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            JSONObject datajsonObject = new JSONObject(qRloginstr);
            JSONObject TokenJson = datajsonObject.getJSONObject("rubbishIn");
            inTime = TokenJson.getString("inTime");
            inCode = TokenJson.getString("inCode");
            incode = inCode;

            } catch (JSONException e) {
            e.printStackTrace();
        }


    }
    private void PrintMessge() {
        // TODO Auto-generated method stub
        printHelper.PrintStringEx(getString(R.string.hosptelname), mTitleTextSize, false, titleBold,mTitleType);
        String str="~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
        //mPrinter.PrintString(str, mValueTextSize);
        printHelper.PrintLineInit(mLineTextSize);
        printHelper.PrintLineStringByType(str, mLineTextSize, PrintHelper.PrintType.Centering, false);
        printHelper.PrintLineEnd();
        printHelper.SetGrayLevel((byte)0x03);
        printHelper.PrintLineInit(mKeyTextSize);
        printHelper.PrintLineStringByType("袋数:", mKeyTextSize, PrintHelper.PrintType.Left, false);
        printHelper.PrintLineString(count.getText().toString(), mKeyTextSize, 80, false);//160
        printHelper.PrintLineEnd();
        printHelper.PrintLineInit(mKeyTextSize);
        printHelper.PrintLineStringByType("时间", mKeyTextSize, PrintHelper.PrintType.Left, false);
        printHelper.PrintLineString(inTime, mKeyTextSize, 100, false);//160
//        printHelper.PrintLineString("入库人：", mKeyTextSize, 200, false);//160
//        printHelper.PrintLineString(App.getApp().getName(), mKeyTextSize, 280, false);//160
        printHelper.PrintLineEnd();
//        printHelper.PrintLineInit(mKeyTextSize);
//        printHelper.PrintLineStringByType("科室：", mKeyTextSize, PrintHelper.PrintType.Left, false);
//        printHelper.PrintLineString(DName, mKeyTextSize, 90, false);//160
//        printHelper.PrintLineEnd();
//        printHelper.PrintLineInit(mKeyTextSize);
//        printHelper.PrintLineStringByType("时间：", mKeyTextSize, PrintHelper.PrintType.Left, false);
//        printHelper.PrintLineString(time, mKeyTextSize, 90, false);//160
//        printHelper.PrintLineEnd();
//        printHelper.PrintLineInit(mKeyTextSize);
//        printHelper.PrintLineStringByType("编码：", mKeyTextSize, PrintHelper.PrintType.Left, false);
//        printHelper.PrintLineString(code, mKeyTextSize, 90, false);//160
//        printHelper.PrintLineEnd();
        Bitmap bm=null;
        try {
            bm = BarcodeUtil.encodeAsBitmap(inCode,
                    BarcodeFormat.CODE_128, 300, 100);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        if(bm!=null)
        {
            printHelper.PrintBitmap(bm);
        }
        printHelper.PrintLineInit(40);
        printHelper.PrintLineStringByType("", mKeyTextSize,PrintHelper.PrintType.Right, true);//160
        printHelper.PrintLineEnd();

        printHelper.printBlankLine(40);
        Handler   mhandler=new Handler();
        mhandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                dismissProgressDialog();
            }
        },2000);


    }
//    private void initPos() {
//        // 获取PosApi实例
//        mPosSDK = PosApi.getInstance(this);
//        // 根据型号进行初始化mPosApi类
//        if (Build.MODEL.contains("LTE")
//                || Build.DISPLAY.contains("3508")
//                || Build.DISPLAY.contains("403")
//                || Build.DISPLAY.contains("35S09")) {
//            mPosSDK.initPosDev("ima35s09");
//        } else if (Build.MODEL.contains("5501")) {
//            mPosSDK.initPosDev("ima35s12");
//        } else {
//            mPosSDK.initPosDev(PosApi.PRODUCT_MODEL_IMA80M01);
//        }
//
//        //监听初始化回调结果
//        mPosSDK.setOnComEventListener(mCommEventListener);
//        // 打印队列初始化
//        mPrintQueue = new PrintQueue(this, mPosSDK);
//        // 打印队列初始化
//        mPrintQueue.init();
//        //打印队列设置监听
//        mPrintQueue.setOnPrintListener(new PrintQueue.OnPrintListener() {
//            //打印完成
//            @Override
//            public void onFinish() {
//                // TODO Auto-generated method stub
//                //打印完成
//                Toast.makeText(getApplicationContext(),
//                        getString(R.string.print_complete), Toast.LENGTH_SHORT)
//                        .show();
//                //当前可打印
//                isCanPrint = true;
//                //完成之后关掉打印功能
////
//            }
//
//            //打印失败
//            @Override
//            public void onFailed(int state) {
//                // TODO Auto-generated method stub
//                isCanPrint = true;
//                switch (state) {
//                    case PosApi.ERR_POS_PRINT_NO_PAPER:
//                        // 打印缺纸
//                        showTipDialog(getString(R.string.print_no_paper));
//                        break;
//                    case PosApi.ERR_POS_PRINT_FAILED:
//                        // 打印失败
//                        showTipDialog(getString(R.string.print_failed));
//                        break;
//                    case PosApi.ERR_POS_PRINT_VOLTAGE_LOW:
//                        // 电压过低
//                        showTipDialog(getString(R.string.print_voltate_low));
//                        break;
//                    case PosApi.ERR_POS_PRINT_VOLTAGE_HIGH:
//                        // 电压过高
//                        showTipDialog(getString(R.string.print_voltate_high));
//                        break;
//                }
//            }
//
//            @Override
//            public void onGetState(int arg0) {
//                // TODO Auto-generated method stub
//
//            }
//
//            //打印设置
//            @Override
//            public void onPrinterSetting(int state) {
//                // TODO Auto-generated method stub
//                isCanPrint = true;
//                switch (state) {
//                    case 0:
//                        Toast.makeText(CheckOutActivity.this, "持续有纸", Toast.LENGTH_SHORT).show();
//                        break;
//                    case 1:
//                        //缺纸
//                        Toast.makeText(CheckOutActivity.this, getString(R.string.no_paper), Toast.LENGTH_SHORT).show();
//                        break;
//                    case 2:
//                        //检测到黑标
//                        Toast.makeText(CheckOutActivity.this, getString(R.string.label), Toast.LENGTH_SHORT).show();
//                        break;
//                }
//            }
//        });
//    }







//    //打印
//    private void Pos() {
//        try {
//            StringBuilder sb = new StringBuilder();
////            sb.append("          医废信息                ");
////            sb.append("\n");
//            sb.append("        启动人民医院      ");
//            sb.append("\n");
//            sb.append("-----------------------------");
//            sb.append("\n");
//            sb.append("重量: " + Weigets + "kg");
//            sb.append("  ");
//            sb.append("袋数: " + DName);
//            sb.append("\n");
//            sb.append("时间: " + time);
//            sb.append("\n");
//            byte[] bt = sb.toString().getBytes("GBK");
//            btMap = encode2dAsBitmap(code, 300, 300, 2);
//            byte[] printData = BitmapTools.bitmap2PrinterBytes(btMap);
//
//            mPosSDK.printText(50, bt, bt.length);
//            // 将打印数组添加到打印队列
//            mPrintQueue.addBmp(40, 40, btMap.getWidth(), btMap.getHeight(),
//                    printData);
//            mPrintQueue.addText(50, "\n\n".getBytes("GBK"));
//
//
//        } catch (
//                UnsupportedEncodingException e)
//
//        {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        mPrintQueue.printStart();
//
//    }
//
//    public static Bitmap encode2dAsBitmap(String contents, int desiredWidth,
//                                          int desiredHeight, int barType) {
//        BarcodeFormat barcodeFormat = BarcodeFormat.CODE_128;
//        if (barType == 1) {
//            barcodeFormat = BarcodeFormat.CODE_128;
//        } else if (barType == 2) {
//            barcodeFormat = BarcodeFormat.QR_CODE;
//        }
//
//        Bitmap barcodeBitmap = null;
//        try {
//            barcodeBitmap = encodeAsBitmap(contents, barcodeFormat,
//                    desiredWidth, desiredHeight);
//        } catch (WriterException e) {
//            e.printStackTrace();
//        }
//
//        return barcodeBitmap;
//    }
//
//    public static Bitmap encodeAsBitmap(String contents, BarcodeFormat format,
//                                        int desiredWidth, int desiredHeight) throws WriterException {
//        final int WHITE = 0xFFFFFFFF;
//        final int BLACK = 0xFF000000;
//
//        HashMap<EncodeHintType, String> hints = null;
//        String encoding = guessAppropriateEncoding(contents);
//        if (encoding != null) {
//            hints = new HashMap<EncodeHintType, String>(2);
//            hints.put(EncodeHintType.CHARACTER_SET, encoding);
//        }
//        MultiFormatWriter writer = new MultiFormatWriter();
//        BitMatrix result = writer.encode(contents, format, desiredWidth,
//                desiredHeight, hints);
//        result = deleteWhite(result);// 删除白边
//        int width = result.getWidth();
//        int height = result.getHeight();
//        int[] pixels = new int[width * height];
//        // All are 0, or black, by default
//        for (int y = 0; y < height; y++) {
//            int offset = y * width;
//            for (int x = 0; x < width; x++) {
//                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
//            }
//        }
//
//        Bitmap bitmap = Bitmap.createBitmap(width, height,
//                Bitmap.Config.ARGB_8888);
//        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
//        return bitmap;
//    }
//
//    private static BitMatrix deleteWhite(BitMatrix matrix) {
//        int[] rec = matrix.getEnclosingRectangle();
//        int resWidth = rec[2] + 1;
//        int resHeight = rec[3] + 1;
//
//        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
//        resMatrix.clear();
//        for (int i = 0; i < resWidth; i++) {
//            for (int j = 0; j < resHeight; j++) {
//                if (matrix.get(i + rec[0], j + rec[1]))
//                    resMatrix.set(i, j);
//            }
//        }
//        return resMatrix;
//    }
//
//    public static String guessAppropriateEncoding(CharSequence contents) {
//        // Very crude at the moment
//        for (int i = 0; i < contents.length(); i++) {
//            if (contents.charAt(i) > 0xFF) {
//                return "UTF-8";
//            }
//        }
//        return null;
//    }

    @Override
    protected void onPause() {
        super.onPause();



        }

    @Override
    protected void onStop() {
        super.onStop();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();


        }

    @Override
    public void onBackPressed() {
        long l = System.currentTimeMillis();
        if (l - this.mPressedBackTime > 3000L) {
            showLongToast("再次轻触返回键退出程序");
            this.mPressedBackTime = l;
            return;
        }
        finish();
    }


}
